package com.cn.wanxi.util;

import java.sql.*;

public class JDBC {
    /**
     * 1.注册驱动
     * 2.链接数据库（url，username，password）
     * 3.编译sql语句
     * 4.执行sql语句
     * 5.得到结果集
     * 6.返回
     */
//    static Connection connection = null;
    static final String URL = "jdbc:mysql://121.199.55.96:3306/canyin04";
    static final String USERNAME = "canyin04";
    static final String PASSWORD = "123456";
//    static PreparedStatement preparedStatement = null;

    private static Connection getConnection() {
        Connection connection = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    public static int update(String sql) {
        Connection connection = getConnection();
        PreparedStatement preparedStatement = null;
        int reuslt = 0;
        try {
            preparedStatement = connection.prepareStatement(sql);
            reuslt = preparedStatement.executeUpdate();//影响数据的条数,新增，修改，删除都用executeUpdate
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return reuslt;
    }

    public static ResultSet findAll(String sql) {
        Connection connection = getConnection();
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            preparedStatement = connection.prepareStatement(sql);
            resultSet = preparedStatement.executeQuery();

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return resultSet;
    }

//    public void close(){
//        if (preparedStatement!=null){
//            try {
//                preparedStatement.close();
//            } catch (SQLException e) {
//                e.printStackTrace();
//            }
//        }
//    }
}
